package com.atguigu.gmall.common.config.thread.config;

import com.atguigu.gmall.common.config.thread.properties.AppThreadProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableConfigurationProperties(AppThreadProperties.class)
public class AppThreadPoolAutoConfiguration {

    /*
        int corePoolSize,
        int maximumPoolSize,
        long keepAliveTime,
        TimeUnit unit,
        BlockingQueue<Runnable> workQueue,
        ThreadFactory threadFactory,
        RejectedExecutionHandler handler
     */
    @Bean
    public ThreadPoolExecutor executor(AppThreadProperties appThreadProperties){
        return new ThreadPoolExecutor(
                appThreadProperties.getCorePoolSize(),
                appThreadProperties.getMaximumPoolSize(),
                appThreadProperties.getKeepAliveTime(),
                TimeUnit.MINUTES,

                new LinkedBlockingQueue<>(appThreadProperties.getCapacity()),
                new ThreadFactory() {
            int i = 1;
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("线程池核心线程为"+i++);
                return thread;
            }

        },
                new ThreadPoolExecutor.CallerRunsPolicy());
    }

}
